<script setup>
import { computed, watch } from 'vue'
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/preview.css'
import './markdown-styles.css'

const props = defineProps({
  message: {
    type: Object,
    required: true
  },
  userInfo: {
    type: Object,
    default: null
  }
})

const userAvatar = computed(() => {
  if (!props.userInfo) return '斌'
  const displayName = props.userInfo.userName || props.userInfo.email || '斌'
  return displayName.charAt(0) || '斌'
})

// 调试：检查消息内容（仅在开发时启用）
if (import.meta.env.DEV) {
  watch(() => props.message.content, (newContent) => {
    if (props.message.role === 'assistant' && newContent) {
      const contentStr = String(newContent)
      console.log(`🔍 [ChatMessage] 组件接收到的内容长度: ${contentStr.length}`)
      console.log(`🔍 [ChatMessage] 组件接收到的内容预览: ${JSON.stringify(contentStr.substring(0, 150))}`)

      // 检查是否有阿拉伯数字
      const arabicNumbers = contentStr.match(/\d+/g)
      if (arabicNumbers) {
        console.log(`🔍 [ChatMessage] 内容中的阿拉伯数字: ${arabicNumbers.join(', ')}`)
      } else {
        // 检查是否包含应该伴随数字的词汇
        if (contentStr.includes('约元') || contentStr.includes('预算') || contentStr.match(/约\d*元/)) {
          console.warn(`⚠️ [ChatMessage] 检测到应该包含数字的文本模式，但未找到阿拉伯数字`)
          console.warn(`⚠️ [ChatMessage] 相关内容: ${JSON.stringify(contentStr.match(/约.{0,10}元/g) || [])}`)
        }
      }
    }
  }, { immediate: true })
}
</script>

<template>
  <div class="chat-item" :class="message.role">
    <div class="message-wrapper">
      <!-- 头像 -->
      <div class="message-avatar">
        <div v-if="message.role === 'assistant'" class="avatar-icon ai">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 2L2 7L12 12L22 7L12 2Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 17L12 22L22 17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M2 12L12 17L22 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <div v-else class="avatar-icon user">
          <img v-if="userInfo?.avatar" :src="userInfo.avatar" class="user-avatar-img" alt="头像">
          <span v-else>{{ userAvatar }}</span>
        </div>
      </div>

      <!-- 消息内容 -->
      <div class="bubble" :class="{ 'streaming': message.isLoading && message.content }">
        <div v-if="message.isLoading && !message.content" class="loading-indicator">
          <div class="loading-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        <div v-else-if="message.role === 'assistant'" class="markdown-content">
          <!-- 直接传递原始内容，不做任何转换 -->
          <MdPreview
            :modelValue="message.content || ''"
            previewTheme="default"
            :showCodeRowNumber="true"
          />
          <!-- 流式输出时显示光标动画 -->
          <span v-if="message.isLoading && message.content" class="typing-cursor">▋</span>
        </div>
        <div v-else class="user-message">
          {{ message.content }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 消息项 */
.chat-item {
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  background-color: #ffffff;
}

/* 消息容器（头像+内容） */
.message-wrapper {
  display: flex;
  gap: 12px;
  width: 100%;
  max-width: 800px;
  padding: 0 24px;
  align-items: flex-start;
}

/* 用户消息靠右 */
.chat-item.user .message-wrapper {
  flex-direction: row-reverse;
  justify-content: flex-start;
}

/* AI消息靠左 */
.chat-item.assistant .message-wrapper {
  flex-direction: row;
  justify-content: flex-start;
}

/* 头像样式 */
.message-avatar {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  overflow: hidden;
}

.avatar-icon.ai {
  background: linear-gradient(135deg, #10a37f 0%, #1a7f64 100%);
  color: #ffffff;
  padding: 6px;
}

.avatar-icon.ai svg {
  width: 22px;
  height: 22px;
}

.avatar-icon.user {
  background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
  color: #ffffff;
}

.user-avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 消息内容容器 */
.bubble {
  max-width: 500px;
  padding: 10px 14px;
  font-size: 15px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  border-radius: 12px;
  display: inline-block;
}

/* 用户消息样式 - 浅灰背景，文本靠右 */
.chat-item.user .bubble {
  background-color: #f3f4f6;
  color: #1f2937;
  text-align: right;
}

/* AI消息样式 - 纯白无背景，文本靠左 */
.chat-item.assistant .bubble {
  background-color: transparent;
  color: #374151;
  padding: 0;
  text-align: left;
  max-width: 100%;
}

/* Markdown 内容容器 */
.markdown-content {
  width: 100%;
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 用户消息样式 */
.user-message {
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 加载动画样式 */
.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0;
}

.loading-dots {
  display: flex;
  gap: 4px;
  align-items: center;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #6b7280;
  animation: loading-bounce 1.4s ease-in-out infinite both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }
.loading-dots span:nth-child(3) { animation-delay: 0s; }

@keyframes loading-bounce {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 流式输出打字光标 */
.typing-cursor {
  display: inline-block;
  margin-left: 2px;
  color: #10a37f;
  animation: cursor-blink 1s infinite;
}

@keyframes cursor-blink {
  0%, 49% {
    opacity: 1;
  }
  50%, 100% {
    opacity: 0;
  }
}
</style>

